package top.malaoshi.netdisk.ctrl;

import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import top.malaoshi.easy.logging.Log;
import top.malaoshi.easy.logging.LogFactory;
import top.malaoshi.netdisk.Constant;
import top.malaoshi.netdisk.service.NoteSrvImpl;
import top.malaoshi.netdisk.validation.ValidGroup;
import top.malaoshi.netdisk.vo.JsonCodeMsg;
import top.malaoshi.netdisk.vo.JsonResult;
import top.malaoshi.netdisk.vo.Note;
import top.malaoshi.netdisk.vo.NoteContent;
import top.malaoshi.util.StringUtil;
import top.malaoshi.util.id.SnowflakeIdWorker;
import top.malaoshi.util.io.Resources;
import top.malaoshi.web.utils.PathUtils;
import top.malaoshi.web.utils.WebServerUtil;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/note")
@Validated
public class NoteCtrl {

    static final Log LOG = LogFactory.getLog(NoteCtrl.class);
    @Resource
    private NoteSrvImpl noteSrv;

    @GetMapping("/list")
    public JsonResult list(String keyword,String typeId) throws Exception {

        List list = noteSrv.query(keyword,typeId);

        return JsonResult.success(null,list);
    }

    @PostMapping("/save")
    @Validated(ValidGroup.Insert.class)
    public JsonResult save(@RequestBody @Valid Note note) throws Exception {

        return noteSrv.save(note);
    }
    @PostMapping("/addContent")
    @Validated(ValidGroup.AddContent.class)
    public JsonResult addContent(@Valid @RequestBody Note note) throws Exception {
        Map map = noteSrv.addContent(note);
        return JsonResult.success("添加成功！",map);
    }
    @PostMapping("/upload")
    public JsonResult upload(MultipartFile image, HttpServletRequest request) throws IOException {
        JsonResult jr = null;
        if(image!=null){
            String tid = request.getParameter("tid");
            String typeId = request.getParameter("typeId");
            String oFilename=image.getOriginalFilename();
            String suffix= StringUtil.lastSlice(oFilename,".",true);
            String newFilename= SnowflakeIdWorker.getRandomStr()+suffix;
            //前台页面回显图片的url
            String imageURL= Constant.DOMAIN+"/upload/" +newFilename;
            File file = PathUtils.getWebRootPath(Constant.UPLOAD);
            //由于设置的临时目录也是该目录，启动服务时，会自动创建临时目录，所以此处可以不用判断
            LOG.debug("上传文件路径："+file.getAbsolutePath());
            if(!file.exists()) {
                LOG.debug("上传文件路径不存在");
                if(file.mkdirs()){
                    LOG.debug("上传文件路径创建成功");
                }else{
                    LOG.debug("上传文件路径创建失败");
                }
            }
            File filePath=new File(file,newFilename);

            Note note = new Note();
            note.setTid(tid);
            note.setTypeId(typeId);
            note.setFile(imageURL);

            try {
                image.transferTo(filePath);
                LOG.debug("移动上传文件到该路径："+filePath.getAbsolutePath());
                Map map = noteSrv.upload(note);
                map.put("file", imageURL);//页面回显图片
                jr = JsonResult.success("上传成功！",map);
            } catch (IOException e) {
                jr = JsonResult.fail(JsonCodeMsg.OPERATE_FAIL.getCode(), "上传失败");
            } catch (Exception e) {
                jr = JsonResult.fail(JsonCodeMsg.OPERATE_FAIL.getCode(), "上传失败");
            }
        }else {
            jr = JsonResult.success("没有上传文件！");
        }
        return jr;
    }
    /**
     * 更新标题
     * @param note
     * @return
     * @throws Exception
     */
    @PostMapping("/updateTitleById")
    @Validated(ValidGroup.UpdateNoteTitle.class)
    public JsonResult updateTitleById( @Valid @RequestBody Note note) throws Exception {

        noteSrv.updateTitleById(note);

        return JsonResult.success("修改成功！");
    }

    /**
     * 修改分类
     * @param note
     * @return
     */
    @PostMapping("/updateTypeById")
    public JsonResult updateTypeById(@Valid @RequestBody Note note) throws SQLException {
        return noteSrv.updateTypeById(note);
    }
    /**
     * 更新内容，根据cid
     * @param noteContent
     * @return
     * @throws Exception
     */
    @PostMapping("/updateContentById")
    public JsonResult updateContentById(@RequestBody NoteContent noteContent) throws Exception {

        noteSrv.updateContentById(noteContent);

        return JsonResult.success("修改成功！");
    }
    @GetMapping("/showById")
    public JsonResult showById(String id) throws Exception {

        JsonResult jr = noteSrv.showById(id);

        return jr;
    }

    /**
     * 将笔记的标题、全部内容删除到回收站
     * @param id note_title的tid
     * @return
     * @throws Exception
     */
    @GetMapping("/recycleTitleById")
    public JsonResult recycleTitleById(String id) throws Exception {

        noteSrv.recycleTitleById(id);

        return JsonResult.success("成功删除到回收站！");
    }
    @GetMapping("/recycleContentById")
    public JsonResult recycleContentById(String id) throws Exception {

        noteSrv.recycleContentById(id);

        return JsonResult.success("成功删除到回收站！");
    }
    @RequestMapping("/deleteById")
    public JsonResult deleteById(String id) throws Exception {

        noteSrv.deleteById(id);

        return JsonResult.success("删除成功！");
    }
}
